package com.zsyc.controller;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ButtonBar.ButtonData;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.zsyc.model.Word;
import com.zsyc.util.FileImporter;
import java.util.ArrayList;

/**
 * 英语学习控制器类
 */
public class EnglishLearningController {
    private static final Logger LOGGER = Logger.getLogger(EnglishLearningController.class.getName());
    
    @FXML private Label selectedFileLabel;
    @FXML private Button importButton;
    @FXML private TextField wordInput;
    @FXML private TextField meaningInput;
    @FXML private TableView<Word> wordTableView;
    @FXML private TableColumn<Word, Integer> idColumn;
    @FXML private TableColumn<Word, String> wordColumn;
    @FXML private TableColumn<Word, String> meaningColumn;
    @FXML private TableColumn<Word, String> timeColumn;
    @FXML private TableColumn<Word, String> actionColumn;
    
    @FXML private ComboBox<Integer> wordCountCombo;
    @FXML private ComboBox<String> difficultyCombo;
    @FXML private Label timeLabel;
    @FXML private Label accuracyLabel;
    @FXML private Button startGameButton;
    @FXML private Button restartButton;
    @FXML private Label gameMessageLabel;
    @FXML private GridPane gameGrid;
    @FXML private VBox gameResultPanel;
    @FXML private Label resultTitleLabel;
    @FXML private Label resultDetailsLabel;
    
    private MainController mainController;
    private File selectedFile;
    private ObservableList<Word> wordList;
    private Timeline gameTimer;
    private int gameStartTime;
    private int correctMatches;
    private int totalPairs;
    private List<Word> gameWords;
    private Button firstSelectedCard;
    private boolean isGameActive;
    
    /**
     * 初始化控制器
     */
    @FXML
    public void initialize() {
        // 初始化单词表格
        setupWordTable();
        
        // 初始化游戏设置
        setupGameSettings();
        
        // 加载单词列表
        refreshWordList();
    }
    
    /**
     * 设置主控制器引用
     */
    public void setMainController(MainController mainController) {
        this.mainController = mainController;
    }
    
    /**
     * 设置单词表格
     */
    private void setupWordTable() {
        wordList = FXCollections.observableArrayList();
        
        idColumn.setCellValueFactory(new PropertyValueFactory<>("wordId"));
        wordColumn.setCellValueFactory(new PropertyValueFactory<>("englishWord"));
        meaningColumn.setCellValueFactory(new PropertyValueFactory<>("chineseMeaning"));
        timeColumn.setCellValueFactory(new PropertyValueFactory<>("createdAt"));
        
        // 设置操作列
        actionColumn.setCellFactory(param -> new TableCell<Word, String>() {
            private final Button deleteButton = new Button("删除");
            {
                deleteButton.setStyle("-fx-background-color: #e74c3c; -fx-text-fill: white;");
                deleteButton.setOnAction(event -> {
                    Word word = getTableView().getItems().get(getIndex());
                    deleteWord(word);
                });
            }
            
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(deleteButton);
                }
            }
        });
        
        wordTableView.setItems(wordList);
    }
    
    /**
     * 设置游戏设置
     */
    private void setupGameSettings() {
        wordCountCombo.setItems(FXCollections.observableArrayList(6, 8, 10, 12));
        wordCountCombo.setValue(8);
        
        difficultyCombo.setItems(FXCollections.observableArrayList("简单", "中等", "困难"));
        difficultyCombo.setValue("中等");
    }
    
    /**
     * 选择单词文件
     */
    @FXML
    private void selectWordFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择单词文件");
        fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("文本文件", "*.txt"),
            new FileChooser.ExtensionFilter("CSV文件", "*.csv"),
            new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        
        selectedFile = fileChooser.showOpenDialog(null);
        if (selectedFile != null) {
            selectedFileLabel.setText(selectedFile.getName());
            importButton.setDisable(false);
        }
    }
    
    /**
     * 导入单词
     */
    @FXML
    private void importWords() {
        if (selectedFile == null) {
            showAlert("请先选择文件", "请选择一个单词文件进行导入。", AlertType.WARNING);
            return;
        }
        
        try {
            List<Word> words = FileImporter.importWordsFromFile(selectedFile);
            if (words.isEmpty()) {
                showAlert("导入失败", "文件中没有找到有效的单词数据。", AlertType.WARNING);
                return;
            }
            
            boolean success = Word.importWords(words);
            if (success) {
                showAlert("导入成功", "成功导入 " + words.size() + " 个单词。", AlertType.INFORMATION);
                refreshWordList();
                selectedFile = null;
                selectedFileLabel.setText("未选择文件");
                importButton.setDisable(true);
            } else {
                showAlert("导入失败", "导入过程中发生错误。", AlertType.ERROR);
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "导入单词失败", e);
            showAlert("导入失败", "导入过程中发生错误：" + e.getMessage(), AlertType.ERROR);
        }
    }
    
    /**
     * 手动添加单词
     */
    @FXML
    private void addWord() {
        String englishWord = wordInput.getText().trim();
        String chineseMeaning = meaningInput.getText().trim();
        
        if (englishWord.isEmpty() || chineseMeaning.isEmpty()) {
            showAlert("输入错误", "请输入英文单词和中文释义。", AlertType.WARNING);
            return;
        }
        
        Word word = new Word(englishWord, chineseMeaning);
        if (word.save()) {
            showAlert("添加成功", "单词添加成功。", AlertType.INFORMATION);
            wordInput.clear();
            meaningInput.clear();
            refreshWordList();
        } else {
            showAlert("添加失败", "单词添加失败，可能已存在相同单词。", AlertType.ERROR);
        }
    }
    
    /**
     * 刷新单词列表
     */
    @FXML
    private void refreshWordList() {
        wordList.clear();
        List<Word> words = Word.getAllWords();
        wordList.addAll(words);
    }
    
    /**
     * 删除单词
     */
    private void deleteWord(Word word) {
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除单词");
        alert.setContentText("确定要删除单词 \"" + word.getEnglishWord() + "\" 吗？");
        
        if (alert.showAndWait().orElse(null) == ButtonType.OK) {
            if (word.delete()) {
                showAlert("删除成功", "单词删除成功。", AlertType.INFORMATION);
                refreshWordList();
            } else {
                showAlert("删除失败", "单词删除失败。", AlertType.ERROR);
            }
        }
    }
    
    /**
     * 清空所有单词
     */
    @FXML
    private void clearAllWords() {
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("确认清空");
        alert.setHeaderText("清空单词库");
        alert.setContentText("确定要清空所有单词吗？此操作不可恢复！");
        
        if (alert.showAndWait().orElse(null) == ButtonType.OK) {
            if (Word.clearAllWords()) {
                showAlert("清空成功", "所有单词已清空。", AlertType.INFORMATION);
                refreshWordList();
            } else {
                showAlert("清空失败", "清空单词库失败。", AlertType.ERROR);
            }
        }
    }
    
    /**
     * 开始游戏
     */
    @FXML
    private void startGame() {
        if (wordList.isEmpty()) {
            showAlert("无法开始游戏", "单词库为空，请先添加一些单词。", AlertType.WARNING);
            return;
        }
        
        int wordCount = wordCountCombo.getValue();
        if (wordCount > wordList.size()) {
            showAlert("单词不足", "单词库中只有 " + wordList.size() + " 个单词，无法开始游戏。", AlertType.WARNING);
            return;
        }
        
        startGameButton.setDisable(true);
        restartButton.setDisable(false);
        gameMessageLabel.setVisible(false);
        gameGrid.setVisible(true);
        gameResultPanel.setVisible(false);
        
        initializeGame(wordCount);
    }
    
    /**
     * 初始化游戏
     */
    private void initializeGame(int wordCount) {
        isGameActive = true;
        correctMatches = 0;
        totalPairs = wordCount;
        
        // 随机选择单词
        gameWords = Word.getRandomWords(wordCount);
        
        // 创建游戏卡片
        createGameCards();
        
        // 开始计时
        startTimer();
    }
    
    /**
     * 创建游戏卡片
     */
    private void createGameCards() {
        gameGrid.getChildren().clear();
        
        // 创建单词和释义的配对
        List<String> cardTexts = new ArrayList<>();
        for (Word word : gameWords) {
            cardTexts.add(word.getEnglishWord());
            cardTexts.add(word.getChineseMeaning());
        }
        
        // 随机打乱顺序
        Random random = new Random();
        for (int i = cardTexts.size() - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            String temp = cardTexts.get(i);
            cardTexts.set(i, cardTexts.get(j));
            cardTexts.set(j, temp);
        }
        
        // 创建网格布局
        int cols = (int) Math.ceil(Math.sqrt(cardTexts.size()));
        int rows = (int) Math.ceil((double) cardTexts.size() / cols);
        
        for (int i = 0; i < cardTexts.size(); i++) {
            Button card = createCard(cardTexts.get(i));
            gameGrid.add(card, i % cols, i / cols);
        }
    }
    
    /**
     * 创建单个卡片
     */
    private Button createCard(String text) {
        Button card = new Button(text);
        card.setPrefSize(120, 80);
        card.setStyle("-fx-font-size: 14px; -fx-background-color: #3498db; -fx-text-fill: white;");
        card.setUserData(text);
        
        card.setOnAction(event -> handleCardClick(card));
        
        return card;
    }
    
    /**
     * 处理卡片点击
     */
    private void handleCardClick(Button card) {
        if (!isGameActive || card.getStyle().contains("#27ae60")) {
            return; // 游戏结束或卡片已匹配
        }
        
        if (firstSelectedCard == null) {
            // 第一张卡片
            firstSelectedCard = card;
            card.setStyle("-fx-font-size: 14px; -fx-background-color: #f39c12; -fx-text-fill: white;");
        } else {
            // 第二张卡片
            if (firstSelectedCard == card) {
                // 点击同一张卡片，取消选择
                firstSelectedCard.setStyle("-fx-font-size: 14px; -fx-background-color: #3498db; -fx-text-fill: white;");
                firstSelectedCard = null;
                return;
            }
            
            // 检查是否匹配
            if (isMatch(firstSelectedCard, card)) {
                // 匹配成功
                firstSelectedCard.setStyle("-fx-font-size: 14px; -fx-background-color: #27ae60; -fx-text-fill: white;");
                card.setStyle("-fx-font-size: 14px; -fx-background-color: #27ae60; -fx-text-fill: white;");
                correctMatches++;
                
                if (correctMatches == totalPairs) {
                    endGame();
                }
            } else {
                // 匹配失败，恢复原样
                firstSelectedCard.setStyle("-fx-font-size: 14px; -fx-background-color: #3498db; -fx-text-fill: white;");
            }
            
            firstSelectedCard = null;
        }
    }
    
    /**
     * 检查两张卡片是否匹配
     */
    private boolean isMatch(Button card1, Button card2) {
        String text1 = (String) card1.getUserData();
        String text2 = (String) card2.getUserData();
        
        for (Word word : gameWords) {
            if ((text1.equals(word.getEnglishWord()) && text2.equals(word.getChineseMeaning())) ||
                (text1.equals(word.getChineseMeaning()) && text2.equals(word.getEnglishWord()))) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 开始计时器
     */
    private void startTimer() {
        gameStartTime = (int) (System.currentTimeMillis() / 1000);
        
        gameTimer = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
            int currentTime = (int) (System.currentTimeMillis() / 1000);
            int elapsed = currentTime - gameStartTime;
            int minutes = elapsed / 60;
            int seconds = elapsed % 60;
            timeLabel.setText(String.format("%02d:%02d", minutes, seconds));
        }));
        gameTimer.setCycleCount(Timeline.INDEFINITE);
        gameTimer.play();
    }
    
    /**
     * 结束游戏
     */
    private void endGame() {
        isGameActive = false;
        gameTimer.stop();
        
        int elapsed = (int) (System.currentTimeMillis() / 1000) - gameStartTime;
        int minutes = elapsed / 60;
        int seconds = elapsed % 60;
        double accuracy = (double) correctMatches / totalPairs * 100;
        
        resultTitleLabel.setText("恭喜！游戏完成！");
        resultDetailsLabel.setText(String.format("用时：%02d:%02d\n正确率：%.1f%%", minutes, seconds, accuracy));
        
        gameGrid.setVisible(false);
        gameResultPanel.setVisible(true);
        
        startGameButton.setDisable(false);
        restartButton.setDisable(true);
    }
    
    /**
     * 重新开始游戏
     */
    @FXML
    private void restartGame() {
        if (gameTimer != null) {
            gameTimer.stop();
        }
        
        gameGrid.setVisible(false);
        gameResultPanel.setVisible(false);
        gameMessageLabel.setVisible(true);
        
        startGameButton.setDisable(false);
        restartButton.setDisable(true);
        
        timeLabel.setText("00:00");
        accuracyLabel.setText("0%");
    }
    
    /**
     * 再来一局
     */
    @FXML
    private void playAgain() {
        startGame();
    }
    
    /**
     * 返回主页
     */
    @FXML
    private void goBack() {
        if (mainController != null) {
            mainController.showMainView();
        } else {
            LOGGER.warning("主控制器引用为空，无法返回主页");
        }
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String content, AlertType type) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}
